package bluejack.operation;
import bluejack.events.OperationEvent;
import nme.events.EventDispatcher;

/**
 * ...
 * @author BlueJack
 */

class Oper extends EventDispatcher, implements IOper
{
	public static inline var NONE:Int = 0;
	public static inline var WAIT:Int = 1;
	public static inline var RUN:Int = 2;
	public static inline var END:Int = 3;
	
	private static var IDS:Int = 0;
	//标示
	public var id:Int;
	//当前所处的队列
	public var queue:Queue;
	//当前状态
	public var step:Int;
	//最后一次的结果
	public var lastResult:Dynamic;
	//是否不等待而立即执行下一个Oper
	public var immediately:Bool;
	//是否在出错的时候继续队列
	public var continueWhenFail:Bool;

	public function new() {
		super();
		id = IDS;
		IDS ++;
		immediately = false;
		continueWhenFail = true;
	}
	
	//立即执行
	public function execute():Void {
		var e:OperationEvent = new OperationEvent(OperationEvent.OPERATION_START);
		e.oper = this;
		dispatchEvent(e);
		if (queue!=null) {
			e = new OperationEvent(OperationEvent.CHILD_OPERATION_START);
			e.oper = queue;
			e.childOper = this;
			queue.dispatchEvent(e);
		}
		step = RUN;
		if (immediately) {	//立即执行则立即触发完成事件
			e = new OperationEvent(OperationEvent.OPERATION_COMPLETE);
			e.oper = this;
			dispatchEvent(e);
			if (queue!=null) {
				e = new OperationEvent(OperationEvent.CHILD_OPERATION_COMPLETE);
				e.oper = queue;
				e.childOper = this;
				dispatchEvent(e);
			}
		}
	}
	
	//成功函数
	public function result(event:Dynamic=null):Void {
		lastResult = event;
		end(event);
		var e:OperationEvent = new OperationEvent(OperationEvent.OPERATION_COMPLETE);
		e.oper = this;
		e.result = event;
		dispatchEvent(e);
		if (queue!=null) {
			e = new OperationEvent(OperationEvent.CHILD_OPERATION_COMPLETE);
			e.oper = queue;
			e.childOper = this;
			e.result = event;
			dispatchEvent(e);
			this.queue = null;
		}
		step = END;
	}
	
	//失败函数
	public function fault(event:Dynamic=null):Void {
		lastResult = event;
		end(event);
		var e:OperationEvent = new OperationEvent(OperationEvent.OPERATION_ERROR);
		e.oper = this;
		e.result = event;
		dispatchEvent(e);
		if (queue!=null) {
			e = new OperationEvent(OperationEvent.CHILD_OPERATION_ERROR);
			e.oper = queue;
			e.childOper = this;
			e.result = event;
			dispatchEvent(e);
			this.queue = null;
		}
		step = END;
	}
	
	/**
	 * 推入队列
	 * @param queue	使用的队列，为空则为默认队列
	 */
	public function commit(queue:Queue = null):Void {
		if (queue==null) queue = Queue.getDefaultQueue();
		queue.commitChild(this);
	}
	
	//结束方法
	private function end(event:Dynamic= null):Void { }
	
	//中断队列
	public function halt():Void {
		end();
		if (queue!=null) queue.haltChild(this);
	}
	
}